// 微信浏览器环境h5微信登录 (只能在微信浏览器嵌套h5的方式才行)
// 静默登录是实现方式
export default {
	data() {
		return {
			isWeixin: false,
		};
	},
	onLoad() {
		this.isWeixin = this.isWechat()
		if (this.isWeixin) {
			this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
		}
	},
	methods: {
		/*微信登录相关  start*/
		//方法：用来判断是否是微信内置的浏览器
		isWechat() {
			return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
		},
		// 方法:用来提取code
		getUrlCode(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
					''
				])[1]
				.replace(/\+/g, '%20')) || null
		},
		// 检查浏览器地址栏中微信接口返回的code
		checkWeChatCode() {
			let code = this.getUrlCode('code')
			uni.showToast({
				title: `微信code=${code}`
			})
			if (code) {
				this.getOpenidAndUserinfo(code)
			}
		},
		// 请求微信接口，用来获取code
		getWeChatCode() {
			let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
			// todo 这个不能写在这
			let appid = 'wx294625b9aabc5902'
			window.location.href = 
			`https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_login&state=1#wechat_redirect`
		},
		// 把code传递给后台接口，静默登录
		getOpenidAndUserinfo(code) {
			this.$http({
				url: 'api/login',
				data: {
					code: code
				}
			}).then((res) => {
				console.log(res)
				if (res.code != 0) {
					uni.showToast({
						title: res.msg,
						duration: 3000,
						icon: 'none'
					});
					return
				} else {
					this.afterLogin(res)
				}
			})
		},
		/*微信登录相关  end*/
		afterLogin(res) {
			let user = res.data.user
			uni.setStorageSync('token', res.data.token);
			let u = {
				avatar: user.avatar ? user.avatar : this.avatar,
				mobile: user.mobile,
				nickname: user.nickname ? user.nickname : '土肥圆'
			}
			uni.setStorage({
				key: 'u',
				data: u,
				success: () => {

					let url = uni.getStorageSync('redirect')
					uni.reLaunch({
						url: url ? url : '/pages/index'
					})
				}
			});
		},
	},

}